import axios from 'axios';
import router from '@/router';
import store from '@/store';
import { Notification, MessageBox } from 'element-ui';
import { serialize } from '@/utils/tools';
import { getToken, setToken } from '@/utils/auth';
import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css';
const noToken = ['/login'];

// create an axios instance
const service = axios.create({
    // baseURL: process.env.VUE_APP_BASE_API, // url
    baseURL: window.server.SERVER_API[0].api, // url
    // withCredentials: true, // send cookies when cross-domain requests
    timeout: 15 * 1000, // request timeout 15s

    validateStatus: status => status >= 200 && status <= 500 // 默认的
});
// NProgress Configuration
NProgress.configure({
    showSpinner: false
});
// request interceptor
service.interceptors.request.use(
    config => {
        NProgress.start(); // start progress bar
        // config.baseURL = getToken('api_domain') ? getToken('api_domain') : 'http://173.16.10.62:8082';
        config.headers['Authentication'] = getToken('auth_key') ? getToken('auth_key') : '';
        config.headers['userId'] = getToken('session_id') ? getToken('session_id') : '';
        config.headers['clientType'] = 0;
        // headers中配置serialize为true开启序列化
        if (config.method === 'post' && config.headers.serialize) {
            config.data = serialize(config.data);
            delete config.data.serialize;
        }
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);
// response interceptor
service.interceptors.response.use(
    response => {
        NProgress.done();
        const res = response.data;
        const message = res.error;
        // 空数据
        if (!res.code) {
            return res;
        }
        if (res.code === 202) {
            Notification({
                title: '提示',
                type: 'error',
                message: '暂无数据'
            });
            // store.dispatch('permission/logout').then(msg => {
            //     router.push('/login');
            // });
            return;
        }
        if (res.code === 201) {
            // Notification({
            //     title: '提示',
            //     type: 'error',
            //     message: '暂无数据'
            // });
            return;
        }
        // 401登录token失效处理
        if (res.code === 555) {
            Notification({
                title: 'token失效',
                type: 'error',
                message: '请重新登录'
            });
            store.dispatch('user/logout').then(msg => {
                this.$message.success(res);
                location.reload();
                this.$router.push('/login');
                // this.getInfo();
            });

            return;
        }
        if (res.code === 402) {
            Notification({
                title: res.msg,
                type: 'error',
                message: '请稍后再试'
            });
            store.dispatch('permission/logout').then(msg => {
                location.reload();
                router.push('/login');
            });
            return;
        }
        // 101接口二次确认处理
        if (res.code === 101) {
            return new Promise((resolve, reject) => {
                MessageBox.confirm(res.error, {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    const params = { ...JSON.parse(response.config.data), is_confirm: 1 }; // 点击确认将is_confirm = 1加入请求参数中
                    response.config.data = JSON.stringify(params);
                    service(response.config).then(res => {
                        resolve(res);
                    }).catch(err => {
                        reject(err);
                    });
                }).catch(() => {
                    console.log('取消按钮');
                });
            });
        }
        // 302重置密码处理
        if (res.code === 302) {
            Notification({
                title: res.msg,
                type: 'info'
            });
            router.push(`/resetpwd?id=${res.data.id}`);
            return;
        }
        // 接口报错处理
        // skipStatusVaild 跳过没有业务状态的判断
        // 例如: 获取图片验证码接口
        if (!response.config.skipStatusVaild && res.code !== 200) {
            Notification({
                title: res.msg,
                message: message,
                type: 'error'
            });
            return Promise.reject(message);
        }
        // 成功回调
        return res;
    },
    error => {
        NProgress.done();
        return Promise.reject(new Error(error));
    }
);

export const getBasicInfo = () => {
    return axios.get(process.env.VUE_APP_BASE_API + '/admin/base/getBusinessInfo', {
        params: {
            // url: location.origin // 正式
            url: 'http://173.16.200.25:4000' // 测试内网
                // url: 'http://123.52.43.196:4006' //测试外网
                // url: 'http://173.16.200.24:4000' // 预发布内网
                // url: 'http://123.52.43.196:4000' // 预发布外网
        },
        headers: {
            'Platform': 'pc'
        }
    });
};

export default service;
